<template>
  <div class="box">
    <el-card shadow class="card">
      <!-- 1.面包屑 -->
      <MyBread url="administrator" level1="教练管理" />
      <!-- 2.搜索 -->
      <el-input
        placeholder="请输入教练姓名"
        v-model="search"
        class="with-input"
        clearable
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="searchUser"
        ></el-button>
      </el-input>
      <!-- 添加教练按钮 -->
      <el-button type="success" plain @click="dialogVisible"
        >添加教练</el-button
      >
      <!-- 3.表格 -->
      <el-table :data="UserData" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="50"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80"></el-table-column>
        <el-table-column prop="identify" label="身份证号" width="230"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column prop="reverseCar" label="预约车辆"></el-table-column>
        <el-table-column label="是否安排练车时间" width="200">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isArranged"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="已安排"
              inactive-text="未安排"
              disabled
              class="switch"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="years" label="教练教龄"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.$index, scope.row)"
              style="margin-right: 10px;"
            ></el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该用户信息吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <el-button
                slot="reference"
                type="danger"
                circle
                icon="el-icon-delete"
              >
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 4.分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="length"
      >
      </el-pagination>
    </el-card>
    <!-- 添加教练的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogCoachFormVisible"
      width="440"
    >
      <el-form :model="CoachInfo" :rules="rules" ref="CoachInfo">
        <el-form-item prop="name">
          <el-input v-model="CoachInfo.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="CoachInfo.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="identify">
          <el-input
            v-model="CoachInfo.identify"
            :disabled="!isAdd"
            placeholder="身份证号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model.number="CoachInfo.phone"
            placeholder="联系电话"
          ></el-input>
        </el-form-item>
        <el-form-item prop="years">
          <el-input
            v-model.number="CoachInfo.years"
            placeholder="教练教龄"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="handleUser()">保存信息</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "CoachUser",
  data() {
    return {
      search: "", // 搜索输入框输入的内容
      isAdd: true, // true：添加 false：更新
      page: 1, // 当前页数
      limit: 2, // 每条页面条数
      length: 0, // 获取数据的长度
      dialogCoachFormVisible: false, // 控制教练对话框的显示与隐藏
      UserData: [], // 请求获取的教练数据
      // 教练表单
      CoachInfo: {
        name: "",
        sex: "男",
        identify: "",
        reverseCar: "",
        isArranged: false,
        progress: 0,
        phone: "",
        years: "",
      },
      // 教练表单验证规则
      rules: {
        // 可以添加身份证号验证规则，样式同phone
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 2, max: 12, message: "长度在2到12个字符", trigger: "blur" },
        ],
        identify: [{ validator: this.validateIdentify, trigger: ["blur", "change"] }],
        phone: [{ validator: this.checkPhone, trigger: ["blur", "change"] }],
        years: [
          { required: true, message: "教龄不能为空", trigger: "blur" },
          { type: "number", message: "必须输入数字", trigger: "blur" },
        ],
      },
      title: "", // 对话框标题：添加还是更新信息
    };
  },
  methods: {
    // 取消添加或更新操作
    cancel() {
      this.dialogCoachFormVisible = false;
      if (!this.isAdd) {
        // 更新操作时取消 -- 重新获取数据
        this.getCoachListData();
        this.getCoachListDataLength();
      } else {
        this.CoachInfo = {
          sex: "男",
          isArranged: false,
          reverseCar: "",
          progress: 0,
        };
      }
    },
    // 获取教练数据长度
    getCoachListDataLength() {
      this.$https
        .getUserData({
          url: "/coach",
          like: this.search,
        })
        .then((res) => {
          this.length = res.data.length;
        });
    },
    // 搜索功能实现
    async searchUser() {
      this.getCoachListDataLength();
      this.limit = 2;
      this.page = 1;
      this.getCoachListData();
      this.search = "";
    },
    // 分页获取教练数据
    getCoachListData() {
      this.$https
        .getUserData({
          url: "/coach",
          page: this.page,
          limit: this.limit,
          like: this.search,
        })
        .then((res) => {
          this.UserData = res.data;
        });
    },
    // 当每页条数发生变化使调用
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.getCoachListData();
    },
    // 当页数发生变化时调用
    handleCurrentChange(val) {
      this.page = val;
      this.getCoachListData();
    },
    // 显示添加教练的对话框
    async dialogVisible() {
      const bool = await this.haveThisPermission(this.$route.path, "添加教练");
      if (!bool) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 清空表单
      this.CoachInfo = {
        sex: "男",
        isArranged: false,
        reverseCar: "",
        progress: 0,
      };
      // 显示添加教练对话框
      this.isAdd = true;
      this.title = "添加教练信息";
      this.dialogCoachFormVisible = true;
    },
    // 添加教练信息到json-server数据库
    addUser() {
      this.$refs["CoachInfo"].validate(async (valid) => {
        if (valid) {
          this.dialogCoachFormVisible = false;
          // 发送数据
          await this.$https.addUserData("/coach", this.CoachInfo);
          // 教练添加成功后，创建账号 -- 封装账户信息,形成默认账号
          const date = new Date();
          let account = {
            username: this.CoachInfo.identify,
            password:
              "j" +
              this.CoachInfo.identify.substring(
                this.CoachInfo.identify.length - 6
              ),
            rolename: "coach",
            createTime:
              date.getFullYear() +
              "-" +
              (date.getMonth() + 1) +
              "-" +
              date.getDate(),
          };
          // 添加账户
          await this.$https.addUserData("/login", account);
          // 重新获取教练数据
          this.page = 1;
          this.search = "";
          this.getCoachListData();
          // 重新获取教练长度
          this.getCoachListDataLength();
          // 提示成功信息
          this.$message.success("教练添加成功");
          // 清空表单
          this.CoachInfo = {
            sex: "男",
            isArranged: false,
            reverseCar: "",
            progress: 0,
          };
        } else {
          this.$message.info("表单验证信息不通过");
        }
      });
    },
    // 根据id更新教练信息到json-server数据库
    updateUser() {
      this.$refs["CoachInfo"].validate(async (valid) => {
        if (valid) {
          this.dialogCoachFormVisible = false;
          // 发送数据
          await this.$https.updateUserData(
            "/coach",
            this.CoachInfo.id,
            this.CoachInfo
          );
          // 重新获取教练数据
          this.page = 1;
          this.search = "";
          this.getCoachListData();
          this.getCoachListDataLength();
          // 清空表单
          this.CoachInfo = {
            sex: "男",
            isArranged: false,
            reverseCar: "",
            progress: 0,
          };
          // 提示信息
          this.$message.success("修改教练成功");
        } else {
          this.$message.info("表单验证信息不通过");
        }
      });
    },
    // 删除教练信息（删除教练权限）
    async handleDelete(_, row) {
      const bool = await this.haveThisPermission(this.$route.path, "删除教练");
      if (!bool) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      await this.$https.deleteUserData("/coach", row.id);
      // 根据教练identify找到账户信息，找到后删除
      const { data } = await this.$https.getUser({ like: row.identify });
      await this.$https.deleteUserData("/login", data[0].id);
      // 重新获取教练数据
      this.page = 1;
      this.search = "";
      this.getCoachListData();
      // 重新获取教练数据长度
      this.getCoachListDataLength();
      // 提示信息
      this.$message.success("教练删除成功");
    },
    // 处理：确定是添加还是更新操作
    handleUser() {
      if (this.isAdd) {
        this.addUser();
      } else {
        this.updateUser();
      }
    },
    // 编辑学员或教练信息 -- 弹出对话框，修改标题，回显数据
    // 修改教练权限
    async handleEdit(_, row) {
      const bool = await this.haveThisPermission(this.$route.path, "修改教练");
      if (!bool) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      this.isAdd = false;
      this.title = "编辑教练信息";
      this.CoachInfo = row;
      this.dialogCoachFormVisible = true;
    },
  },
  mounted() {
    // 获取教练信息总长度
    this.getCoachListDataLength();
    // 获取教练数据
    this.getCoachListData();
  },
};
</script>

<style scoped>
.box,
.card {
  height: 100%;
}
.with-input {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-right: 10px;
}
.pagination {
  margin-top: 30px;
}
</style>